package com.systemCapacity.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.systemCapacity.common.dto.AttributeDto;
import com.systemCapacity.common.dto.BlueAttributeDto;
import com.systemCapacity.common.dto.BlueEquipmentDto;
import com.systemCapacity.common.dto.EquipmentDto;
import com.systemCapacity.entity.Attribute;
import com.systemCapacity.entity.Device;
import com.systemCapacity.entity.Enum.AttributeType;
import com.systemCapacity.entity.Equipment;
import com.systemCapacity.mapper.EquipmentMapper;
import com.systemCapacity.service.AttributeService;
import com.systemCapacity.service.DeviceService;
import com.systemCapacity.service.EquipmentService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
public class EquipmentServiceImpl extends ServiceImpl<EquipmentMapper, Equipment> implements EquipmentService {

    @Autowired
    private EquipmentMapper equipmentMapper;

    @Autowired
    private AttributeService attributeService;

    @Autowired
    private DeviceService deviceService;

    @Override
    public List<EquipmentDto> getChildEquipment(String pTemplateId) {
        QueryWrapper<Equipment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("pTemplateId", pTemplateId);
        List<Equipment> equipments = equipmentMapper.selectList(queryWrapper);
        List<EquipmentDto> dtos = equipments.stream()
                .map(equipment -> BeanUtil.copyProperties(equipment, EquipmentDto.class))
                .collect(Collectors.toList());
        for (EquipmentDto dto : dtos) {
            dto.setAttributes(attributeService.getEquipmentAttributes(dto.getEquipmentId()));
        }
        return dtos;
    }

    @Override
    public boolean equipmentExist(String equipmentId) {
        QueryWrapper<Equipment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("equipmentId", equipmentId);
        return getOne(queryWrapper) != null;
    }

    @Override
    public boolean equipmentNameExist(String equipmentName) {
        QueryWrapper<Equipment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("equipmentName", equipmentName);
        return getOne(queryWrapper) != null;
    }

    @Override
    @Transactional
    public boolean saveEquipment(EquipmentDto dto) {
        Equipment equipment = new Equipment();
        equipment.setEquipmentId(UUID.randomUUID().toString());
        equipment.setEquipmentName(dto.getEquipmentName());
        equipment.setWeight(dto.getWeight());
        equipment.setPTemplateId(dto.getTemplateId());
        save(equipment);
        for (AttributeDto attribute : dto.getAttributes()) {
            attribute.setAttributeType(AttributeType.EQUIPMENT);
            attributeService.saveAttribute(equipment.getEquipmentId(), attribute);
        }
        return false;
    }

    @Override
    @Transactional
    public boolean editEquipment(EquipmentDto dto) {
        LambdaUpdateWrapper<Equipment> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(Equipment::getEquipmentId, dto.getEquipmentId())
                .set(Equipment::getEquipmentName, dto.getEquipmentName());
        update(lambdaUpdateWrapper);
        for (AttributeDto attribute : dto.getAttributes()) {
            attributeService.editAttribute(attribute);
        }
        return true;
    }

    @Override
    @Transactional
    public boolean deleteEquipmentByEquipmentId(String equipmentId) {
        //删除参数
        QueryWrapper<Attribute> attributeQueryWrapper = new QueryWrapper<>();
        attributeQueryWrapper.eq("equipmentId",equipmentId);
        List<Attribute> attributeList = attributeService.list(attributeQueryWrapper);
        for (Attribute attribute : attributeList) {
            attributeService.removeById(attribute.getAttributeId());
            deviceService.deleteIfNotExists(attribute.getDeviceId());
        }

        //删除装备
        QueryWrapper<Equipment> equipmentQueryWrapper = new QueryWrapper<>();
        equipmentQueryWrapper.eq("equipmentId",equipmentId);
        remove(equipmentQueryWrapper);
        return true;
    }

    @Override
    @Transactional
    public boolean editBlueEquipment(List<BlueEquipmentDto> equipmentList) {
        for (BlueEquipmentDto dto : equipmentList) {
            if("delete".equals(dto.getOperation())){
                //删除装备下面所有参数
                LambdaQueryWrapper<Attribute> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(Attribute::getDeviceId,dto.getDeviceId())
                        .eq(Attribute::getEquipmentId,dto.getEquipmentId());
                attributeService.remove(queryWrapper);
                deviceService.deleteIfNotExists(dto.getDeviceId());
                continue;
            }
            if(dto.getAttributeList() != null && !dto.getAttributeList().isEmpty()){
                //删除装备下面所有参数
                LambdaQueryWrapper<Attribute> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(Attribute::getDeviceId, dto.getDeviceId())
                        .eq(Attribute::getEquipmentId,dto.getEquipmentId());
                attributeService.remove(queryWrapper);
                deviceService.deleteIfNotExists(dto.getDeviceId());

                //添加设备
                Device device = deviceService.saveIfNotExists(dto);
                List<BlueAttributeDto> list = dto.getAttributeList().stream().filter(x -> !StringUtils.isEmpty(x.getAttributeName())).collect(Collectors.toList());
                if(list.isEmpty()){
                    Attribute attribute = new Attribute();
                    attribute.setEquipmentId(dto.getEquipmentId());
                    attribute.setEquipmentName(dto.getEquipmentName() != null ? dto.getEquipmentName().trim() : dto.getEquipmentName());
                    attribute.setDeviceId(device.getDeviceId());
                    attribute.setAttributeType(AttributeType.EQUIPMENT);
                    attribute.setAttributeValueType(null);
                    attribute.setValue(null);
                    if(attribute.getAttributeId() == null){
                        attribute.setAttributeId(UUID.randomUUID().toString());
                    }
                    attributeService.save(attribute);
                    continue;
                }
                for (BlueAttributeDto blueAttributeDto : list) {
                    blueAttributeDto.setEquipmentId(dto.getEquipmentId());
                    blueAttributeDto.setEquipmentName(dto.getEquipmentName());
                    blueAttributeDto.setDeviceId(device.getDeviceId());
                }
                attributeService.editBlueAttribute(list);
            }
        }
        return true;
    }

    @Override
    @Transactional
    public boolean editDataLinkAttr(List<AttributeDto> attributeList){
        for (AttributeDto attributeDto : attributeList) {
            if("delete".equals(attributeDto.getOperation())){
                LambdaQueryWrapper<Attribute> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(Attribute::getAttributeId,attributeDto.getAttributeId());
                attributeService.remove(queryWrapper);
            }else{
                Attribute attribute = new Attribute();
                BeanUtils.copyProperties(attributeDto,attribute);
                List<Double> values = attributeDto.getValues();
                String valueStr = "";
                if (!values.isEmpty()) {
                    valueStr = values.stream().map(x -> x.toString()).collect(Collectors.joining(";"));
                }
                attribute.setValue(valueStr);
                attribute.setAttributeType(AttributeType.EQUIPMENT);
                if(attribute.getAttributeId() == null){
                    attribute.setAttributeId(UUID.randomUUID().toString());
                }
                attributeService.saveOrUpdate(attribute);
            }
        }
        return true;
    }

    /**
     * 查询作战装备所属装备模型
     * @param ids 作战装备id
     * @return 作战装备所属平台类型
     */
    @Override
    public List<String> getEquipmentTemplates(List<String> ids) {
        if (ids.isEmpty()) {
            return new ArrayList<>();
        }
        QueryWrapper<Equipment> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("equipmentId", ids);
        queryWrapper.select("DISTINCT pTemplateId");
        return equipmentMapper.selectList(queryWrapper).stream().
                map(Equipment::getPTemplateId).collect(Collectors.toList());
    }
}
